import { is } from '@electron-toolkit/utils';
import { app } from 'electron';
import Logger from 'electron-log';
import fs from 'fs';
import { mkdirp } from 'mkdirp';
import path from 'path';

// 配置日志
const allowedLevels = ['error', 'warn', 'info', 'debug', 'verbose'] as const;
// 类型推断

type LogLevel = (typeof allowedLevels)[number];
const envLevel = process.env.LOG_LEVEL?.toLowerCase();
const logLevel: LogLevel = allowedLevels.includes(envLevel as LogLevel) ? (envLevel as LogLevel) : 'info';

Logger.transports.file.resolvePathFn = () => {
  const installDir = !is.dev && app.isPackaged ? path.dirname(app.getPath('exe')) : app.getAppPath();
  return path.join(installDir, 'logs', 'main.log');
};
Logger.transports.file.level = logLevel;
Logger.transports.file.maxSize = process.env.LOG_MAX_SIZE ? Number(process.env.LOG_MAX_SIZE) : 10 * 1024 * 1024; // 10MB
Logger.transports.file.format = process.env.LOG_FORMAT || '[{y}-{m}-{d} {h}:{i}:{s}] [{level}] {text}';

class Log {
  private logger: typeof Logger;
  private initialized: boolean = false;

  constructor() {
    this.logger = Logger;
    this.init();
  }

  private async init(): Promise<void> {
    if (!this.initialized) {
      const logDir = path.dirname(this.getLogPath());
      if (!fs.existsSync(logDir)) {
        await mkdirp(logDir);
      }
      this.initialized = true;
    }
  }

  // 信息日志
  info(message: string, ...args: any[]): void {
    this.logger.info(message, ...args);
  }

  // 警告日志
  warn(message: string, ...args: any[]): void {
    this.logger.warn(message, ...args);
  }

  // 错误日志
  error(message: string, ...args: any[]): void {
    this.logger.error(message, ...args);
  }

  // 调试日志
  debug(message: string, ...args: any[]): void {
    this.logger.debug(message, ...args);
  }

  // 详细日志
  verbose(message: string, ...args: any[]): void {
    this.logger.verbose(message, ...args);
  }

  // 设置日志级别
  setLevel(level: 'error' | 'warn' | 'info' | 'debug' | 'verbose'): void {
    this.logger.transports.file.level = level;
  }

  // 获取日志文件路径
  getLogPath(): string {
    return this.logger.transports.file.getFile().path;
  }

  // 清空日志
  clear(): void {
    const logPath = this.getLogPath();
    if (fs.existsSync(logPath)) {
      fs.writeFileSync(logPath, '');
    }
  }
}

// 导出单例
export const log = new Log();
